#include "../server.hpp"

class EchoServer
{
private:
    TcpServer _server;

    void OnCreate(const PtrConnection& pcon)
    {
        DBG_LOG("OnCreate");
    }

    void OnMessage(const PtrConnection& pcon, Buffer* buf)
    {
        DBG_LOG("OnMessage");
        char buffer[2048] = {0};
        buf->Read(buffer, buf->GetReadableSize());
        cout << "server recv: " << buffer << endl;

        string echostr (buffer);
        pcon->Send((char*)echostr.c_str(), echostr.size());
        
        //buf->Write((void*)echostr.c_str(), echostr.size());   不仅写错了buffer（in_buffer）而且还没发出去！！！
    }

    void OnClosed(const PtrConnection& pcon)
    {
        DBG_LOG("OnClosed");
    }

public:
    EchoServer(uint16_t port): _server(port)
    {
        _server.SetConnectedCallback(std::bind(&EchoServer::OnCreate, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
        _server.SetClosedCallback(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
        _server.EnableInactiveRelease(30);
        _server.SetThreadCount(2);
    }

    void Start(){_server.Start();} 
};

